package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
	"time"
)

type CourseContentController struct {
	BaseController
}

func (u *CourseContentController) Prepare() {
	u.BaseController.Prepare()
	u.checkLogin()
	u.checkAuthor("DataGrid")
}

func (u *CourseContentController) Index() {
	u.Data["pageTitle"] = "课程文章"
	u.ActiveSidebarUrl()
	u.Data["canEdit"] = u.checkActionAuthor(u.controllerName, "Edit")
	u.Data["canDelete"] = u.checkActionAuthor(u.controllerName, "Edit")
	u.setTpl("course_content/index")
}

func (u *CourseContentController) DataGrid() {
	var params = models.CourseContentQueryParam{}
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)
	data, total := models.CourseContentPageList(&params)

	u.BootstrapJson(total, data)
}

func (u *CourseContentController) ItemData() {
	data, _ := models.ContentDataList()
	u.jsonResult(enums.JRCodeSuccess, "", data)
}

func (u *CourseContentController) Edit() {
	if u.Ctx.Request.Method == "POST" {
		u.Save()
	}
	Id, _ := u.GetInt(":id", 0)
	m := &models.CourseContent{}
	var err error
	if Id > 0 {
		m, err = models.CourseContentOne(Id)
		if err != nil {
			u.pageError("数据无效，请刷新后重试")
		}
	} else {
		//m.Status = enums.Enabled
	}
	u.Data["m"] = m

	u.setTpl("course_content/edit", "shared/layout_pullbox")
}

func (u *CourseContentController) Save() {
	m := models.CourseContent{}
	o := orm.NewOrm()
	var err error

	if err = u.ParseForm(&m); err != nil {
		u.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}

	if m.Id == 0 {
		m.CreateAt = time.Now().Unix()
		m.SysUserId = u.curUser.Id
		if _, err := o.Insert(&m); err != nil {
			u.jsonResult(enums.JRCodeFailed, "添加失败", m.Id)
		}
	} else {
		oM, err := models.CourseContentOne(m.Id)
		if err != nil {
			u.jsonResult(enums.JRCodeFailed, "数据无效，请刷新后重试", m.Id)
		}
		m.CreateAt = oM.CreateAt
		m.SysUserId = oM.SysUserId
		if _, err := o.Update(&m); err != nil {
			u.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}

	}
	u.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
}

func (u *CourseContentController) Match() {
	if u.Ctx.Request.Method == "POST" {
		u.MatchSave()
	}

	Id, _ := u.GetInt(":id", 0)
	m, err := models.CourseOne(Id)
	if err != nil {
		u.jsonResult(enums.JRCodeFailed, "数据有误", m.Id)
	}

	u.Data["m"] = m
	u.setTpl("course_content/match", "shared/layout_pullbox")
}

func (u *CourseContentController) MatchSave() {
	Id, err := u.GetInt("Id", 0)
	if err != nil {
		u.jsonResult(enums.JRCodeFailed, "信息不能为空", Id)
	}
	contentId, err := u.GetInt("CourseContentId")
	if err != nil {
		u.jsonResult(enums.JRCodeSuccess, "请选择文章", contentId)
	}
	o := orm.NewOrm()
	m := models.Course{Id: Id}
	if o.Read(&m) == nil {
		m.CourseContentId = contentId
		if _, err := o.Update(&m, "course_content_id"); err != nil {
			u.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}
		u.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
	} else {
		u.jsonResult(enums.JRCodeFailed, "不存在的记录", m.Id)
	}
}

func (u *CourseContentController) Delete() {
	str := u.GetString("ids", "")
	ids := make([]int, 0, len(str))

	for _, item := range strings.Split(str, ",") {
		if id, err := strconv.Atoi(item); err == nil {
			ids = append(ids, id)
		}
	}

	query := orm.NewOrm().QueryTable(models.CourseContentTBName())
	if _, err := query.Filter("id__in", ids).Delete(); err == nil {
		u.jsonResult(enums.JRCodeSuccess, fmt.Sprintf("删除成功"), 0)
	} else {
		u.jsonResult(enums.JRCodeFailed, "删除失败", 0)
	}
}
